package lee.vioson.remotedata.repositories

import android.content.Context
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import lee.vioson.remotedata.ApiServices
import lee.vioson.remotedata.manager.UserManager
import lee.vioson.remotedata.utils.body

/**
 *Author:viosonlee
 *Date:2023/6/10
 *DESCRIPTION:
 */
class RegisterRepositoryImpl(private val context: Context, private val apiServices: ApiServices) :
    RegisterRepository,
    BaseRepository() {
    override fun sendEmailCode(uniqueId: String, email: String): Flow<Boolean> = flow {
        emit(
            handleResponse(
                apiServices.sendEmailCode(
                    mapOf(
                        "uniqueId" to uniqueId,
                        "email" to email
                    ).body
                )
            ).success
        )
    }

    override fun register(
        uniqueId: String,
        email: String,
        password: String,
        emailCode: String,
        customerSource: String,
        areaCode: String,
        language: String
    ) = flow {
        val result = handleNotEmptyResponse(
            apiServices.register(
                mapOf(
                    "uniqueId" to uniqueId,
                    "email" to email,
                    "password" to password,
                    "emailCode" to emailCode,
                    "customerSource" to customerSource,
                    "areaCode" to areaCode,
                    "language" to language,
                ).body
            )
        )
        UserManager.INSTANCE.saveEmailLoginResult(context, result)
        emit(result)
    }

    override fun setPassword(
        uniqueId: String,
        email: String,
        password: String,
        emailCode: String
    ) = flow {
        val result = handleNotEmptyResponse(
            apiServices.forgetPassword(
                mapOf(
                    "uniqueId" to uniqueId,
                    "email" to email,
                    "password" to password,
                    "emailCode" to emailCode,
                ).body
            )
        )
        UserManager.INSTANCE.saveEmailLoginResult(context, result)
        emit(result)
    }
}